import json
import logging
import os
import sys
import threading
import time

from flask import Flask, request, jsonify, Response

from logger.log_manager import setup_logging
from manager.query_manager import query_by_message_id
from processer.file_watcher import start_watching

# 初始化 Flask 应用
app = Flask(__name__)

# 初始化日志
setup_logging()


# 默认路由
@app.route('/', methods=['GET'])
def default_query():
    response = {
        "message_id": "",
        "files": [],
        "status": "success",
        "error": "欢迎使用报关系统"
    }
    return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), 200


# 查询路由
@app.route('/query', methods=['GET'])
def query():
    message_id = request.args.get('message_id', '').strip()
    if not message_id:
        response = {
            "message_id": "",
            "files": [],
            "status": "failed",
            "error": "MessageId 不能为空"
        }
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), 400

    try:
        json_result = query_by_message_id(message_id)
        result = json.loads(json_result)
        return jsonify(result)
    except Exception as e:
        logging.error(f"查询 MessageId '{message_id}' 时出错: {e}")
        response = {
            "message_id": message_id,
            "files": [],
            "status": "failed",
            "error": str(e)
        }
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), 500


@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查请求中是否包含 'upload_dir' 参数
    upload_dir = request.form.get('upload_dir')
    if not upload_dir:
        response = {
            "message": "缺少上传目录参数 'upload_dir'",
            "result": None,
            "code": 400
        }
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), 400

    # 确保上传目录存在
    os.makedirs(upload_dir, exist_ok=True)

    # 检查是否有文件在请求中
    if 'file' not in request.files:
        response = {
            "message": "缺少文件部分 'file'",
            "result": None,
            "code": 400
        }
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), 400

    file = request.files['file']
    if file.filename == '':
        response = {
            "message": "文件名为空",
            "result": None,
            "code": 400
        }
        return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), 400

    # 上传文件路径
    filename = file.filename
    logging.info(f"Received Upload File Request: {upload_dir}/{filename}")

    # 构造文件保存路径
    file_path = os.path.join(upload_dir, filename)
    # 保存文件
    file.save(file_path)

    response = {
        "message": "文件上传成功",
        "result": {"file_path": file_path},
        "code": 200
    }
    return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), 200


# 启动 HTTP API 服务
def start_api_server():
    logging.info("启动 HTTP API 服务...")
    app.run(host='0.0.0.0', port=5410, threaded=True)


# 程序主入口
def main():
    # 启动文件监听线程
    try:
        watching_thread = threading.Thread(target=start_watching, name="FileWatcherThread", daemon=True)
        watching_thread.start()
    except Exception as e:
        logging.error(f"启动文件监听失败: {e}")
        sys.exit(1)

    # 等待文件监听线程启动完成
    time.sleep(1)

    # 检查文件监听线程是否仍然存活
    if not watching_thread.is_alive():
        logging.error("文件监听线程启动失败，程序退出")
        sys.exit(1)

    # 启动 HTTP API 服务线程
    try:
        api_thread = threading.Thread(target=start_api_server, name="APIServerThread", daemon=True)
        api_thread.start()
        logging.info("HTTP API 服务已启动。")
    except Exception as e:
        logging.error(f"启动 HTTP API 服务失败: {e}")
        sys.exit(1)

    # 防止主线程退出，确保守护线程可以继续运行
    try:
        while True:
            pass
    except KeyboardInterrupt:
        logging.info("程序被用户中断，正在退出...")
        sys.exit(0)


if __name__ == "__main__":
    main()